package com.dreamer.view.wxmall;

import com.dreamer.domain.comment.Comment;
import com.dreamer.domain.pmall.goods.GoodsStandard;
import com.dreamer.domain.pmall.goods.PmallGoods;
import com.dreamer.domain.pmall.goods.PmallGoodsType;
import com.dreamer.domain.pmall.order.Order;
import com.dreamer.domain.pmall.shopcart.CartItem;
import com.dreamer.domain.pmall.shopcart.ShopCart;
import com.dreamer.domain.system.SystemParameter;
import com.dreamer.domain.user.*;
import com.dreamer.domain.wxmall.CommentDTO;
import com.dreamer.domain.wxmall.ShopCatDTO;
import com.dreamer.domain.wxmall.UserDTO;
import com.dreamer.repository.system.SystemParameterDAOInf;
import com.dreamer.repository.user.AddressDAO;
import com.dreamer.service.Comment.CommentHandler;
import com.dreamer.service.mobile.*;
import com.dreamer.service.mobile.factory.WxConfigFactory;
import com.dreamer.view.pmall.dto.PointsGoodsDTO;
import com.wxjssdk.JSAPI;
import com.wxjssdk.dto.SdkResult;
import net.sf.json.JSONObject;
import org.apache.commons.collections.map.HashedMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
import ps.mx.otter.exception.ApplicationException;
import ps.mx.otter.exception.DataNotFoundException;
import ps.mx.otter.utils.SearchParameter;
import ps.mx.otter.utils.WebUtil;
import ps.mx.otter.utils.message.Message;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

@RestController
@RequestMapping(value = {"/discountMall", "/dmz/discountMall"})
public class DiscountMallController {

    @Autowired
    private MallGoodsHandler mallGoodsHandler;

    @Autowired
    private MallGoodsTypeHandler mallGoodsTypeHandler;

    @Autowired
    private SystemParameterDAOInf systemParameterDAO;

    @Autowired
    private CommentHandler commentHandler;

    //PMCART 购物车常量
    private static final String PMCART = "pmshopcart";

    @Autowired
    private AgentHandler agentHandler;

    @Autowired
    private AddressMyHandler addressMyHandler;

    @Autowired
    private OrderHandler orderHandler;

    @Autowired
    private AddressCloneHandler addressCloneHandler;

    @Autowired
    private AddressDAO addressDAO;

    @Autowired
    private WxConfigFactory wxConfigFactory;

    /**
     * 前端产品分类和主推产品合并接口
     * @param param
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/homePage.json",method = RequestMethod.GET)
    public Map homePageShow(@ModelAttribute("parameter") SearchParameter<PmallGoods> param) {
        Map resMap = new HashedMap();
        List typeList = new ArrayList();
        List<PmallGoodsType> list = mallGoodsTypeHandler.findSubType();
        if(list!=null&&!list.isEmpty()){
            Map map = new HashedMap();
            map.put("goodsType.id",list.get(0).getId());
            map.put("shelf",true);
            List<PmallGoods> ms = mallGoodsHandler.getList(map);
            List<PointsGoodsDTO> dtos = new ArrayList<>();
            ms.forEach(g -> {
                if(!g.getShelf()){ return; }
                PointsGoodsDTO dto = new PointsGoodsDTO();
                dto.setId(g.getId());
                dto.setName(g.getName());
                dto.setSel(g.getSel());
                dto.setPrice(g.getPrice());
                dto.setRetailPrice(g.getRetailPrice());
                dto.setShareName(g.getShareName());
                dto.setShareDetail(g.getShareDetail());
                dto.setPrice(g.getPrice());
                dto.setSpec(g.getSpec());
                dto.setStockQuantity(g.getStockQuantity());
                dto.setVouchers(g.getVouchers());
                String imgUrl = g.getImgFile();
                String wallImgUrl = g.getWallFile();
                dto.setImgUrl(imgUrl);
                dto.setWallImgUrl(wallImgUrl);
                dtos.add(dto);
            });
            /*Iterator<PmallGoodsType> iterator = list.iterator();
            while (iterator.hasNext()){
                PmallGoodsType pmallGoodsType = iterator.next();
                if("今日主推".equals(pmallGoodsType.getName())){
                    iterator.remove();
                }
            }*/
            for (int i = 0 ; i <list.size() ; i++ ) {
                Map goodsTypeMap = new HashedMap();
                goodsTypeMap.put("id",list.get(i).getId());
                goodsTypeMap.put("name",list.get(i).getName());
                typeList.add(goodsTypeMap);
            }
            resMap.put("goodsType",typeList);
            resMap.put("ztGoods",dtos);
        }
        return resMap;
    }

    /**
     * 前端幻灯片接口
     * @param param -code幻灯片的代码ID
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value="/imgBanner.json",method = RequestMethod.GET)
    public List imgBannerList(@ModelAttribute("parameter")SearchParameter<SystemParameter> param, HttpServletRequest request){
        List list = new ArrayList();
        try{
            //TODO SystemParameter code=16 正式的时候可以重新定义 写死
            SystemParameter sysParams= systemParameterDAO.findById("16");
            WebUtil.turnPage(param, request);
            String[] img = sysParams.getParamValue().split("\\+");
            for (int i = 0 ; i <img.length ; i++ ) {
                list.add(i,img[i]);
            }
        }catch(Exception exp){
            exp.printStackTrace();
        }
        return list;
    }

    /**
     * 优惠商城产品详细信息接口
     * @param id -产品ID
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/goodsDetail.json",method = RequestMethod.GET)
    public Map goodsDetail(@RequestParam("id") Integer id) {
        Map detailMap = new HashedMap();
        PmallGoods g = mallGoodsHandler.get(id);
        PointsGoodsDTO dto = new PointsGoodsDTO();
        //dto.setId(g.getId());
        dto.setDateInfo(g.getDateInfo());
        dto.setPrice(g.getPrice());
        dto.setName(g.getName());
        dto.setRetailPrice(g.getRetailPrice());
        dto.setSpec(g.getSpec());
        dto.setStockQuantity(g.getStockQuantity());
        dto.setShareDetail(g.getShareDetail());
        dto.setShareName(g.getShareName());
        dto.setSel(g.getSel());
        dto.setShelf(g.getShelf());
        dto.setGoodsStandard(g.getGoodsStandards());
        dto.setVouchers(g.getVouchers());
        dto.setImgUrl(g.getImgFile());
        List<String> list = new ArrayList<>();
        if (g.getDetailImg() != null) {
            for (String str : g.getDetailImg().split("\\+")) {
                list.add( str);
            }
        }
        dto.setDetailImgUrls(list);
        //TODO 获取当前产品的评论信息
        List<Comment> comments = commentHandler.findByGid(1,id,100);
        List<CommentDTO> commentDTOList = new ArrayList<>();
        for (Comment comment : comments) {
            CommentDTO commentDTO = new CommentDTO();
            commentDTO.setId(comment.getId());
            commentDTO.setAgentId(comment.getAgent().getId());
            commentDTO.setAgentName(comment.getAgent().getRealName());
            commentDTO.setHeadImage(comment.getAgent().getHeadimgurl());
            commentDTO.setBody(comment.getBody());
            commentDTOList.add(commentDTO);
        }
        detailMap.put("goodsDetail",dto);
        detailMap.put("banner",list);
        detailMap.put("goodsComments",commentDTOList);
        return detailMap;
    }

    /**
     * 优惠商城添加购物车返回状态
     * @param goodsId
     * @param standardIds
     * @param standardPrices
     * @param standardNames
     * @param quantity
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/addCartStatus.json", method = RequestMethod.GET)
    public Map addGoodsToCartStatus(@RequestParam("goodsId") Integer goodsId,
                                  @RequestParam(value = "standardIds[]", required = false) Integer[] standardIds,
                                  @RequestParam(value = "standardPrices[]", required = false) Double[] standardPrices,
                                  @RequestParam(value = "standardNames[]", required = false) String[] standardNames,
                                  @RequestParam(value = "quantity", required = false) Integer quantity, HttpServletRequest request) {
        Map cartMap = new HashedMap();
        boolean msg = false;
        try {
            PmallGoods goods = mallGoodsHandler.get(goodsId);
            if (Objects.isNull(goods)) {
                throw new DataNotFoundException("商品不存在");
            }
            Object ob = WebUtil.getSessionAttribute(request, PMCART);
            ShopCart cart;
            if (Objects.nonNull(ob)) {
                cart = (ShopCart) ob;
            } else {
                cart = new ShopCart();
            }
            Integer addQuantity;
            Set<GoodsStandard> goodsStandards = new HashSet<>();
            String no = String.valueOf(goodsId);
            if(standardIds != null) {
                for(int i=0; i<standardIds.length; i++) {
                    no += "_" + standardIds[i];
                    GoodsStandard goodsStandard=new GoodsStandard();
                    goodsStandard.setId(standardIds[i]);
                    goodsStandard.setPrice(standardPrices[i]);
                    goodsStandard.setName(standardNames[i]);
                    goodsStandards.add(goodsStandard);
                }
            }
            if (Objects.isNull(quantity)) {
                addQuantity = 1;
            } else {
                addQuantity = quantity;
                cart.removeItems(no);
            }
            cart.addGoods(no, goods, addQuantity, goodsStandards);
            WebUtil.addSessionAttribute(request, PMCART, cart);
            ShopCart shopCart = (ShopCart) WebUtil.getSessionAttribute(request, PMCART);
            Map<String, CartItem> cartMaps = shopCart.getItems();
            Set<String> keySet = cartMaps.keySet();
            List<ShopCatDTO> list = new ArrayList<>();
            for(String keys:keySet){
                CartItem cartItem = cartMaps.get(keys);
                ShopCatDTO shopCatDTO = new ShopCatDTO();
                shopCatDTO.setGoodsId(Integer.parseInt(keys));
                shopCatDTO.setPrice(cartItem.getGoods().getPrice());
                shopCatDTO.setQuantity(cartItem.getQuantity());
                shopCatDTO.setName(cartItem.getGoods().getName());
                shopCatDTO.setImgFile(cartItem.getGoods().getImgFile());
                list.add(shopCatDTO);
            }
            if(cart != null){
                msg = true;
                cartMap.put("msg",msg);
                /*if(msg == true){
                    cartMap.put("goodsCart",list);
                }else{
                    msg = false;
                    cartMap.put("msg",msg);
                }*/
            }else{
                cartMap.put("msg",msg);
            }
        } catch (Exception exp) {
            exp.printStackTrace();
        }
        return cartMap;
    }

    /**
     * 购物车中的产品-移除
     * @param goodsId 产品ID
     * @param standardIds  规格IDS[]
     * @param request
     * @return
     */
    @RequestMapping(value = "/rmCart.json", method = RequestMethod.POST)
    public Message rmCart(@RequestParam("goodsId") Integer goodsId,
                          @RequestParam(value = "standardIds[]", required = false) Integer[] standardIds,
                          HttpServletRequest request) {
        try {
            PmallGoods goods = mallGoodsHandler.get(goodsId);
            if (Objects.isNull(goods)) {
                throw new DataNotFoundException("商品不存在");
            }
            //TODO 从缓存中取出购物车数据
            Object object = WebUtil.getSessionAttribute(request, PMCART);
            if (Objects.nonNull(object)) {
                ShopCart cart = (ShopCart) object;
                String no = goods.getId() + "";
                if (standardIds != null) {
                    for (Integer i : standardIds) {
                        no += "_" + i;
                    }
                }
                if(no != null && cart != null){
                    cart.removeItems(no);
                }
                //TODO 存
                WebUtil.addSessionAttribute(request, PMCART, cart);
            }
            return Message.createSuccessMessage();
        } catch (Exception exp) {
            exp.printStackTrace();
            return Message.createFailedMessage(exp.getMessage());
        }
    }

    /**
     * 优惠商城添加购物车取数据
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/addCart.json", method = RequestMethod.GET)
    public Map addGoodsToCart(HttpServletRequest request) {
        Map cartMap = new HashedMap();
        ShopCart shopCart = (ShopCart) WebUtil.getSessionAttribute(request, PMCART);
        Map<String, CartItem> cartMaps = shopCart.getItems();
        Set<String> keySet = cartMaps.keySet();
        List<ShopCatDTO> list = new ArrayList<>();
        for(String keys:keySet){
            CartItem cartItem = cartMaps.get(keys);
            ShopCatDTO shopCatDTO = new ShopCatDTO();
            shopCatDTO.setPrice(cartItem.getGoods().getPrice());
            shopCatDTO.setQuantity(cartItem.getQuantity());
            shopCatDTO.setName(cartItem.getGoods().getName());
            shopCatDTO.setImgFile(cartItem.getGoods().getImgFile());
            shopCatDTO.setGoodsId(cartItem.getGoods().getId());
            list.add(shopCatDTO);
        }
        if(list != null){
            cartMap.put("shopCart",list);
        }else{
            cartMap.put("shopCart","购物车没有数据，请添加！");
        }
        return cartMap;
    }

    /**
     * 优惠商城当前用户的地址信息
     * @param request
     * @return
     */
    @RequestMapping(value = "/address.json")
    public Map myAddressList(HttpServletRequest request) {
        //User user = (User) WebUtil.getCurrentUser(request);
        //Agent agent = agentHandler.get(user.getId());
        Map map = new HashedMap();
        Agent agent = agentHandler.get(36916);
        List<AddressMy> myAddressList = addressMyHandler.findAddressByAgent(agent);
        for (AddressMy addressMy : myAddressList) {
            List list = new ArrayList();
            //todo 一条一条展示
            Address address = new Address();
            address.setId(addressMy.getId());
            address.setConsignee(addressMy.getConsignee());
            address.setMobile(addressMy.getMobile());
            address.setCountry(addressMy.getCountry());
            address.setProvince(addressMy.getProvince());
            address.setCity(addressMy.getCity());
            address.setCounty(addressMy.getCounty());
            address.setAddress(addressMy.getAddress());
            address.setConsigneeCode(addressMy.getConsigneeCode());
            address.setPost_code(addressMy.getPost_code());
            list.add(address);
            map.put("address",list);
        }
        return map;
    }

    /**
     * 提交订单前校验总金额是否正确
     * @param goodsIds
     * @param quantitys
     * @param amount
     * @return
     */
    @RequestMapping(value = "/commitOrderBefore.json",method = RequestMethod.GET)
    //public Map commitOrderBefore( List<Integer> goodsIds, List<Integer> quantitys, Double amount){
    public Map commitOrderBefore(@RequestParam("goodsIds") Integer[] goodsIds, @RequestParam("quantitys[]") Integer[] quantitys, Double amount){
        Map map = new HashedMap();
        if(goodsIds != null && quantitys != null){
            for(int i=0;i<goodsIds.length;i++){
                PmallGoods pmallGoods = mallGoodsHandler.get(goodsIds[i]);
                for(int j=0;j<quantitys.length;j++){
                    Integer quantity = quantitys[j];
                    Double backAmount = pmallGoods.getPrice() * quantity;
                    if(backAmount != amount){
                        map.put("msg","总金额错误!");
                    }else{
                        map.put("msg","true");
                    }
                }
            }
        }
        return map;
    }



    /**
     * 优惠商城删除地址信息
     * @param addressId
     * @return
     */
    @RequestMapping(value = "/rmAddress.json",method = RequestMethod.POST)
    public Message rmAddress(Integer addressId) {
        try{
            Address address = addressDAO.findById(addressId);
            addressDAO.delete(address);
            ps.mx.otter.utils.message.Message message = ps.mx.otter.utils.message.Message.createSuccessMessage();
            message.setData(String.valueOf(address.getId()));
            return message;
        }catch (Exception e){
            e.printStackTrace();
            return ps.mx.otter.utils.message.Message.createFailedMessage(e.getMessage());
        }
    }

    /**
     * 优惠商城添加地址信息
     * @param address
     * @return
     */
    @RequestMapping(value = "/saveAddress.json",method = RequestMethod.POST)
    public Message saveAddress(Address address) {
        try{
            addressDAO.save(address);
            ps.mx.otter.utils.message.Message message = ps.mx.otter.utils.message.Message.createSuccessMessage();
            message.setData(String.valueOf(address.getId()));
            return message;
        }catch (Exception e){
            e.printStackTrace();
            return ps.mx.otter.utils.message.Message.createFailedMessage(e.getMessage());
        }
    }

    /**
     * 优惠商城修改地址信息
     * @param addressId
     * @return
     */
    @RequestMapping(value = "/updateAddress.json",method = RequestMethod.POST)
    public Message updateAddress(Integer addressId) {
        try{
            Address address = addressDAO.findById(addressId);
            addressDAO.merge(address);
            ps.mx.otter.utils.message.Message message = ps.mx.otter.utils.message.Message.createSuccessMessage();
            message.setData(String.valueOf(address.getId()));
            return message;
        }catch (Exception e){
            e.printStackTrace();
            return ps.mx.otter.utils.message.Message.createFailedMessage(e.getMessage());
        }
    }

    /**
     * 优惠商城购物车提交订单-结算
     * @param addressMy
     * @param remark
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/commitOrder.json",method = RequestMethod.POST)
    public Message commitOrder(AddressMy addressMy, String remark, HttpServletRequest request) {
        ShopCart cart = (ShopCart) WebUtil.getSessionAttribute(request, PMCART);
        if (Objects.isNull(cart)) {
            throw new ApplicationException("登陆超时,请重新加入购物车!");
        }
        try {
            //User user = (User) WebUtil.getCurrentUser(request);
            //Agent agent = agentHandler.get(user.getId());
            Agent agent = agentHandler.get(36916);
            addressMy.setAgent(agent);
            AddressClone address = addressCloneHandler.getFromAddressMy(addressMy);
            Order order = orderHandler.commitOrder(agent, address, cart, remark);
            ps.mx.otter.utils.message.Message message = ps.mx.otter.utils.message.Message.createSuccessMessage();
            message.setData(String.valueOf(order.getId()));
            WebUtil.removeSessionAttribute(request, PMCART);
            return message;
        } catch (Exception e) {
            e.printStackTrace();
            return ps.mx.otter.utils.message.Message.createFailedMessage(e.getMessage());
        }
    }



    /**
     * 微信支付完成后，回调支付方法
     * @param body
     * @return
     */
    @RequestMapping("/wxPay.json")
    public String wxPay(@RequestBody(required = false) String body) {
        try {
            String result = orderHandler.payOrderByWx(body);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "<xml>\n" + "  <return_code><![CDATA[SUCCESS]]></return_code>\n" + "  <return_msg><![CDATA[OK]]></return_msg>\n" + "</xml>";
    }

    /**
     * 代金券支付完成后，回调支付方法
     * @param id 订单ID
     * @param accountsType 账户类型
     * @param request
     * @return
     */
    @RequestMapping("/accountsPay.json")
    public Message accountsPay(Integer id, Integer accountsType, HttpServletRequest request) {
        try {
            //User user = (User) WebUtil.getCurrentUser(request);
            Order order = orderHandler.get(id);
            /*if (!order.getUser().getId().equals(user.getId())) {
                throw new ApplicationException("当前订单中用户和当前用户不匹配");
            }*/
            //todo ------暂时定义
            int zmzCode = 36916;
            if (!order.getUser().getId().equals(zmzCode)){
                throw new ApplicationException("当前订单中用户和当前用户不匹配");
            }
            //todo 代金券支付 传入的accountsType=1
            orderHandler.payOrderByAccounts(id, accountsType);
        } catch (Exception e) {
            e.printStackTrace();
            return Message.createFailedMessage(e.getMessage());
        }
        return Message.createSuccessMessage();
    }









    @ResponseBody
    @RequestMapping(value = "/wxLogin.json",method = RequestMethod.GET)
    public Map wxLogin(@RequestParam(required = false) String code, HttpServletRequest request) {
        Map loginMap = new HashedMap();
        System.out.println("++++++++++++++++++++++code+++++++++++++++++++++++++"+code);
        if (code == null) {
            loginMap.put("msg","wxLogin失败，没有获取code，请截图发给管理员1");
            return loginMap;
        }

        SdkResult result = JSAPI.getTokenAndOpenId(wxConfigFactory.getBaseConfig().getAppid(), wxConfigFactory.getBaseConfig().getSecret(), code);
        if (!result.isSuccess()) {
            loginMap.put("msg",result.getError() + ",请截图发给管理员2");
            return loginMap;
        }
        JSONObject json = JSONObject.fromObject(result.getData());
        String openid = json.getString("openid");
        System.out.println("++++++++++++++++++++++openid+++++++++++++++++++++++++"+openid);
        String access_token = json.getString("access_token");
        System.out.println("++++++++++++++++++++++access_token+++++++++++++++++++++++++"+access_token);
        //调用授权接口获取用户基本信息
        result = JSAPI.getSnsUserInfo(access_token, openid);
        if (!result.isSuccess()) {
            loginMap.put("msg",result.getError() + ",请截图发给管理员3");
            return loginMap;
        }
        json = JSONObject.fromObject(result.getData());
        String nickname = json.getString("nickname");
        String headimgurl = json.getString("headimgurl");
        String unionid = json.getString("openid");
        //获取的信息加入session中存储
        request.getSession().setAttribute("s_openid", openid);
        request.getSession().setAttribute("s_nickname", nickname);
        request.getSession().setAttribute("s_headimgurl", headimgurl);
        request.getSession().setAttribute("s_unionid", unionid);
        //以统一Id为标准登陆
        Agent findAgent = agentHandler.get("wxUnionID", unionid);
        String redirectUrl = (String) request.getSession().getAttribute("redirectUrl");
        //系统存在这个用户
        if (findAgent != null) {
            //登录
            if("整顿".equals(findAgent.getAgentStatus().getDesc())){
                loginMap.put("msg","您的账号有异常，请截图发给管理员");
                return loginMap;
            }
            WebUtil.addCurrentUser(request, findAgent);
            WebUtil.login(request);
            //跳转到要跳转的页面
            System.out.println("++++++++++++++++++++++sessionId+++++++++++++++++++++++++"+request.getSession().getId());
            return loginMap;
        } else {//新用户或者没绑定的用户  去登陆页面一键登录 或者登陆绑定
            if (redirectUrl.indexOf("pmall") > -1) {
                //可以一键授权登录
                loginMap.put("isPmall", true);
            }
            return loginMap;
        }
    }


    //手机端登陆 一定要绑定openId，unionId
    @RequestMapping(value = "/login.json", method = RequestMethod.POST)
    @ResponseBody
    public Map mobileLogin(HttpServletRequest request, @RequestParam("accountName") String name, @RequestParam("password") String pwd, HttpServletResponse response) {
        Map map = new HashedMap();
        //获取登陆的跳转地址
        String redirectUrl = (String) request.getSession().getAttribute("redirectUrl");
        response.setHeader("location", redirectUrl);
        try {
            Agent agent = agentHandler.login(name, pwd);
            String s_unionid = (String) request.getSession().getAttribute("s_unionid");
            String s_openid = (String) request.getSession().getAttribute("s_openid");
            String s_headimgurl = (String) request.getSession().getAttribute("s_headimgurl");
            String s_nickname = (String) request.getSession().getAttribute("s_nickname");
            if (s_unionid != null && !s_unionid.equals("")) {
                //绑定opengId
                agent.setWxOpenid(s_openid);
                agent.setWxUnionID(s_unionid);
                agent.setHeadimgurl(s_headimgurl);
                agent.setNickName(s_nickname);
            }
            //保存Agent
            agentHandler.merge(agent);
            //登陆
            WebUtil.addCurrentUser(request, agent);
            WebUtil.login(request);
            User user = (User) WebUtil.getCurrentUser(request);
            UserDTO userDTO = new UserDTO();
            userDTO.setId(user.getId());
            userDTO.setRealName(user.getRealName());
            userDTO.setNickName(user.getNickName());
            userDTO.setHeadimgurl(user.getHeadimgurl());
            userDTO.setMobile(user.getMobile());
            userDTO.setWxOpenid(user.getWxOpenid());
            userDTO.setWxUnionID(user.getWxUnionID());
            userDTO.setLoginToken(user.getLoginToken());
            map.put("user",userDTO);
            map.put("msg","登录成功");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }

    //积分商城过来的用户可以一键授权登陆  还有一个任务就是绑定上级
    @RequestMapping("/dmz/mobile/oAuthLogin.html")
    public String oAuthLogin(HttpServletRequest request) {
        Integer refCode = (Integer) request.getSession().getAttribute("refCode");
        String unionId = (String) request.getSession().getAttribute("s_unionid");
        String openId = (String) request.getSession().getAttribute("s_openid");
        String headerImg = (String) request.getSession().getAttribute("s_headimgurl");
        String nickName = (String) request.getSession().getAttribute("s_nickname");
        Agent agent = agentHandler.createVisitor(unionId, openId, nickName, headerImg, String.valueOf(refCode));
        WebUtil.addCurrentUser(request, agent);
        WebUtil.login(request);
        String redirect = (String) request.getSession().getAttribute("redirectUrl");
        return "redirect:" + redirect;
    }


    //注册
    @RequestMapping("/mobile/register.html")
    public String toRegister(@RequestParam(required = false) String s_unionid, @RequestParam(required = false) String s_openid, @RequestParam(required = false) String refCode, Model model) {
        //TODO 这里有问题
        if (s_openid != null) {
            model.addAttribute("s_unionid", s_unionid);
            model.addAttribute("s_openid", s_openid);
            model.addAttribute("refCode", refCode);//推荐过来的
        }
        return "mobile/register";
    }

    //注册并且绑定上级
    @RequestMapping("/mobile/register.json")
    @ResponseBody
    public Message register(Agent agent, HttpServletRequest request, HttpServletResponse response, String refCode) {

//        String refCode = (String) request.getSession().getAttribute("refCode");
        if (refCode == null) return Message.createFailedMessage("没有推荐人，请联系管理员");
        if (agent.getWxUnionID() == null) return Message.createSuccessMessage("没有WxUnionID，联系管理员");
        try {
            Agent newAgent = agentHandler.selfRegister(agent, refCode);
            String redirectUrl = (String) request.getSession().getAttribute("redirectUrl");
            if (redirectUrl == null) {
                redirectUrl = ServletUriComponentsBuilder.fromContextPath(request).path("/mobile/my.html").build().toString();
            }
            WebUtil.addCurrentUser(request, newAgent);
            WebUtil.login(request);
            response.setHeader("Location", redirectUrl);
            return Message.createSuccessMessage();
        } catch (Exception e) {
            e.printStackTrace();
            return Message.createFailedMessage(e.getMessage());
        }
    }



}
